package com.markhsiu.minimq.serialize.jdk;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.markhsiu.minimq.core.exeption.MiniMQException;
import com.markhsiu.minimq.message.Message;
import com.markhsiu.minimq.serialize.SerializeCodec;

/**
 * JDK序列化
 * @author Mark Hsiu
 *
 */
public class JdkCodec implements SerializeCodec<Message> {

	private static final SerializeCodec<Message> codec = new JdkCodec();

	public static SerializeCodec<Message> OneInstance() {
		return codec;
	}

	@Override
	public byte[] serialize(Message message) throws IOException {
		if (message == null) {
			throw new MiniMQException();
		}

		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;
		try {
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(message);
			return baos.toByteArray();
		} catch (IOException e) {
			throw new MiniMQException(e);
		} finally {
			if (oos != null)
				try {
					oos.close();
					baos.close();
				} catch (IOException e) {
				}
		}
	}

	@Override
	public Message deserialize(byte[] data) throws IOException {
		ObjectInputStream ois = null;
		ByteArrayInputStream bais = null;
		try {
			bais = new ByteArrayInputStream(data);
			ois = new ObjectInputStream(bais);
			
			return (Message) ois.readObject();
		} catch (Exception e) {
			throw new MiniMQException(e);
		} finally {
			if (ois != null)
				try {
					ois.close();
					bais.close();
				} catch (IOException e) {
				}
		}
	}

}
